package com.hjli.filter;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hjli.common.ShareValues;
import com.hjli.model.ArticleCommentInfo;
import com.hjli.model.ArticleInfo;
import com.hjli.model.ArticleInfoStr;
import com.hjli.model.LinkInfo;
import com.hjli.model.UserMacInfo;
import com.hjli.service.impl.ArticleService;
import com.hjli.service.impl.CommentService;
import com.hjli.service.impl.LinkService;
import com.hjli.service.impl.UserMacService;
import com.hjli.tool.FileTool;
import com.hjli.tool.PropertiesTool;
import com.hjli.tool.SysInfoTool;
import com.hjli.tool.TemplateTool;

public class UrlFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		// 初始化application

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// 获取到请求的地址
		String getURL = req.getRequestURI();
		if (getURL.contains(".html")) {
			// 数据库存储的地址
			String dbUrlName = getURL.substring(getURL.lastIndexOf("html/"));

			// 文件名
			String htmlFileName = dbUrlName.substring(dbUrlName.lastIndexOf("/") + 1);
			try {
				createHtml(req, resp, request, response, chain, dbUrlName, htmlFileName);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	// 在文件夹没有时创建
	public void createHtml(HttpServletRequest req, HttpServletResponse resp, ServletRequest request,
			ServletResponse response, FilterChain chain, String dbUrlName, String htmlFileName) throws Exception {
		// 获取到文章的信息
		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-mybatis*.xml");
		ArticleService articleService = (ArticleService) ctx.getBean("articleService");
		CommentService commentService = (CommentService) ctx.getBean("commentService");
		UserMacService userMacService = (UserMacService) ctx.getBean("userMacService");

		ArticleInfoStr articleInfo = articleService.findByUrl(dbUrlName);

		List<ArticleCommentInfo> commentList = commentService.findCommentByAid(articleInfo.getId());
		if(commentList.size()>0&&commentList!=null){
			for(ArticleCommentInfo comment : commentList){
				comment.setcEmail(toStar(comment.getcEmail()));
			}
		}
		List<ArticleCommentInfo> commentStrList = commentService.findCommentInfoByCount(10);
		List<String> strList = new ArrayList<String>();
		for (ArticleCommentInfo comment : commentStrList) {
			strList.add(comment.getcName() + "：“" + comment.getcContent() + "”");
		}

		LinkService linkService = (LinkService) ctx.getBean("linkService");
		List<LinkInfo> linkList = linkService.findByCount(10);

		// 文章tags
		String tags = articleInfo.getaTags();
		String[] tag = tags.split(",");
		List<String> tagList = new ArrayList<String>();
		if (tag.length > 0) {
			for (int i = 0; i < tag.length; i++) {
				tagList.add(tag[i].toString());
			}
		}
		Map<String, Object> templateMap = new HashMap<String, Object>();
		HttpSession session = req.getSession();
		if (session.getAttribute("shareValue") == null) {
			// 页面共同值
			String webroot = req.getContextPath();
			ShareValues shareValues = new ShareValues();
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setCopyright(new String(webproperty.getProperty("copyright").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setWebroot(webroot);
			shareValues.setTitle(articleInfo.getaTitle() + " | " + shareValues.getWebname());
			shareValues.setArticleList(articleService.pageList(0, 10));
			shareValues.setCommentStrList(strList);
			shareValues.setLinkList(linkList);
			shareValues.setKeywords(shareValues.getWebname() + "," + tags + "," + articleInfo.getaTitle());
			shareValues.setDescription(shareValues.getWebname() + "," + articleInfo.getaTitle());
			templateMap.put("values", shareValues);
			session.setAttribute("shareValue", shareValues);
		} else {
			ShareValues shareValues = (ShareValues) session.getAttribute("shareValue");
			shareValues.setTitle(articleInfo.getaTitle() + " | " + shareValues.getWebname());
			templateMap.put("values", shareValues);
		}
		
		String macAddress = SysInfoTool.getMacAddress();
		if (userMacService.findByMac(articleInfo.getId(),macAddress) < 1) {
			articleService.updateViewNum(articleInfo.getId());
			UserMacInfo userMacInfo = new UserMacInfo();
			userMacInfo.setMac(macAddress);
			userMacInfo.setaId(articleInfo.getId());
			userMacService.insert(userMacInfo);
		}
		templateMap.put("article", articleInfo);
		templateMap.put("tagList", tagList);
		templateMap.put("commentList", commentList);
		
		if (session.getAttribute("themeName") == null) {
			Properties property = PropertiesTool.getProperty("theme.properties");
			session.setAttribute("themeName", property.getProperty("themeName"));
			TemplateTool.print(templateMap, "page/templates/themes/" + property.getProperty("themeName") + "",
					"article.ftl", req, resp);
		} else {
			TemplateTool.print(templateMap, "page/templates/themes/" + (String) session.getAttribute("themeName") + "",
					"article.ftl", req, resp);
		}

	}
	public String toStar(String email){
		String dealStr = email.split("@")[0].toString();
		String suffix = "@"+email.split("@")[1].toString();
		if(dealStr.length()<=3){
			dealStr = dealStr.substring(0, dealStr.length()-1)+"***"+suffix;
		}else{
			dealStr = dealStr.substring(0, 3)+"***"+suffix;
		}
		return dealStr;
	}
}
